package com.outsourcing.bottle.ui;

import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.EducationInfo;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.SchoolEntry;
import com.outsourcing.bottle.domain.SchoolInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class SettingEducationActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener {

	private RelativeLayout statusLayout;
	private TextView statusView;
	private ImageView addView;
	private EditText editView;
	private ListView listView;
	
	private final int init_school_info = 1;
	private final int error = 2;
	private final int set_school = 3;
	private final int add_school = 4;
	private final int delete_school = 5;
	private Handler handler;
	private List<SchoolEntry> schoolList;
	private String status;
	private String[] statuses;
	private HashMap<String, String> paramsMap;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.setting_education);
		handler = new Handler(this);
		statuses = new String[] {
				getString(R.string.setting_education_primary),
				getString(R.string.setting_education_junior),
				getString(R.string.setting_education_senior),
				getString(R.string.setting_education_college),
				getString(R.string.setting_education_graduated),
				getString(R.string.setting_education_others) };
		paramsMap = new HashMap<String, String>();
		initWidget();
		UICore.eventTask(this, this, init_school_info, "init_school_info", null);
	}
	
	private void initWidget() {
		LoginUserInfoTable userTable = new LoginUserInfoTable();
		LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
		if (userEntry.getBasicinfo_fullfill() == 1) {
			((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.GONE);
		} else {
			((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.VISIBLE);
			((TextView)findViewById(R.id.tv_profile_tips)).setText(userEntry.getBasicinfo_tip());
		}
		RemoteImageView img_head = (RemoteImageView) findViewById(R.id.iv_author_photo);
		String avatar = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()).getAvatar();
		if (TextUtil.notEmpty(avatar)) {
			img_head.setDefaultImage(R.drawable.avatar_default_small);
			img_head.setImageUrl(avatar);
		}
		statusLayout = (RelativeLayout) findViewById(R.id.setting_education_status_layout);
		statusLayout.setOnClickListener(this);
		statusView = (TextView) findViewById(R.id.setting_education_status_value);
		addView = (ImageView) findViewById(R.id.setting_education_add);
		addView.setOnClickListener(this);
		editView = (EditText) findViewById(R.id.setting_education_edit);
		editView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					if (editView.getText().toString().trim().equals("")) {
						onToast(getString(R.string.setting_school_search_error));
						return true;
					}
					UICore.eventTask(SettingEducationActivity.this, SettingEducationActivity.this, add_school, "add_school", null);
				}
				return false;
			}
		});
		listView = (ListView) findViewById(R.id.setting_education_list);
	}
	
	public void back(View v) {
		finish();
	}
	
	public void confirm(View v) {
		if (!paramsMap.containsKey("status")) {
			onToast(getString(R.string.setting_education_status_error));
			return;
		}
		UICore.eventTask(this, this, set_school, "set_school", null);
	}
	
	@Override
	public void onClick(View v) {
		if (v == statusLayout) {
			doStatusAction();
		} else if (v == addView) {
			if (editView.getText().toString().trim().equals("")) {
				onToast(getString(R.string.setting_school_search_error));
				return;
			}
			UICore.eventTask(this, this, add_school, "add_school", null);
		}
	}
	
	private void doStatusAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, statuses);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						int currentItem;
						if (which == statuses.length) {
							currentItem = 0;
						} else {
							currentItem = which + 1;
						}
						paramsMap.put("status", String.valueOf(currentItem));
						statusView.setText(statuses[which]);
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	} 
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_school_info:
			initEducationInfo();
			break;
		case add_school:
			addSchool();
			break;
		case delete_school:
			deleteSchool((String) obj);
			break;
		case set_school:
			setEducationInfo();
			break;
		default:
			break;
		}
	}
	
	private void addSchool() {
		String url = UrlConfig.add_school_info;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("school", editView.getText().toString().trim());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject object = new JSONObject(result);
				JSONObject resultObj = object.getJSONObject("results");
				if (resultObj.getInt("success") == 0) {
					Message msg = Message.obtain(handler, error, resultObj.getString("errmsg"));
					handler.sendMessage(msg);
				} else {
					getLoginUserInfo();
					Message msg = Message.obtain(handler, add_school, resultObj.getString("successmsg"));
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_school_info:
			if (status != null) {
				statusView.setText(status);
			}
			if (schoolList != null && !schoolList.isEmpty()) {
				SchoolAdapter adapter = new SchoolAdapter();
				listView.setAdapter(adapter);
			}
			break;
		case error:
			onToast((String) msg.obj);
			break;
		case add_school:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, init_school_info, "init_school_info", null);
			break;
		case delete_school:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, init_school_info, "init_school_info", null);
			break;
		case set_school:
			onToast((String) msg.obj);
			break;
		default:
			break;
		}
		return false;
	}

	private void initEducationInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_edu_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				SchoolInfo info = gson.fromJson(result, SchoolInfo.class);
				if (info.getResults().getAuthok() == 0) {
					Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
					handler.sendMessage(msg);
				} else {
					EducationInfo eduInfo = info.getEdu_info();
					status = eduInfo.getStatus();
					schoolList = eduInfo.getMyschools_list();
					handler.sendEmptyMessage(init_school_info);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void deleteSchool(String schoolid) {
		String url = UrlConfig.delete_school_info;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("schoolid", schoolid);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		getLoginUserInfo();
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, delete_school, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setEducationInfo() {
		String url = UrlConfig.set_edu_info;
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		getLoginUserInfo();
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, set_school, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getLoginUserInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class);
			if (loginUserInfo.getResults().getAuthok() == 1) {
				LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
				if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) {
					loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid());
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				} else {
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class SchoolAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return schoolList.size();
		}

		@Override
		public Object getItem(int position) {
			return schoolList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.setting_listitem, null);
			}
			TextView school = (TextView) convertView.findViewById(R.id.setting_listitem_name);
			ImageView add = (ImageView) convertView.findViewById(R.id.setting_listitem_image);
			final SchoolEntry entry = schoolList.get(position);
			if (entry != null) {
				school.setText(entry.getSchool());
				add.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int schoolid = entry.getSchoolid();
						UICore.eventTask(SettingEducationActivity.this,
								SettingEducationActivity.this, delete_school, "delete_school", String.valueOf(schoolid));
					}
				});
			}
			return convertView;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 0) {
			UICore.eventTask(this, this, init_school_info, "init_school_info", null);
		}
	}
}
